-- AutoDeleteMail.lua

-- BUTTONS
Global("CollectButton", nil)
Global("MailList", {} )

Global( "IsRunned", false )
Global( "DelIndex", 0)

-- LOCALIZATION
Global( "localization", "eng" )

--------------------------------------------------------------------------------
-- USER PROCEDURES
--------------------------------------------------------------------------------

-- AO game Localization detection by SLA. Version 2011-02-10.
function GetGameLocalization()
	local B = cartographer.GetMapBlocks()
	local T = { rus="\203\232\227\224", eng="Holy Land", ger="Heiliges Land",
	fra="Terre Sacr\233e", br="Terra Sagrada", jpn="\131\74\131\106\131\65" }
	for b in B do for l,t in T do
	if userMods.FromWString( cartographer.GetMapBlockInfo(B[b]).name ) == t
	then return l end end end return "eng"
end

-- Gets localized text string where @text - string ID
function GetLocalizedText( text )
	return common.GetAddonRelatedTextGroup( localization ):GetText( text )
end


--ExportRaid
function ExportRaid()
	if raid.IsExist() then
		local strout = "RaidPresence: "
		local groups = raid.GetMembers () 
		for key, value in groups do
			local group = value
			for key, value in group do
				local y = userMods.FromWString(value.name)
				strout = strout .. "NOM " .. y .. " "
			end
		end
		
		common.LogInfo(" ", strout)
	else 
		common.LogInfo(" ", "Raid n'existe pas")
	end
end

--ExportRaid slash command
function UnknowSlashCommand( params )
	if userMods.FromWString(params.text) == "/ExportRaid" then
		ExportRaid()
	end
end

--------------------------------------------------------------------------------
-- EVENT HANDLERS
--------------------------------------------------------------------------------

-- SCRIPT_ADDON_INFO_REQUEST
function OnAMAddonInfoRequest( params )
	if params.target == common.GetAddonName() then
		userMods.SendEvent( "SCRIPT_ADDON_INFO_RESPONSE", {
			sender = params.target,
			desc = userMods.FromWString( GetLocalizedText( "Description" ) ),
		} )
	end
end

-- SCRIPT_ADDON_MEM_REQUEST
function OnAMAddonMemoryRequest( params )
	if params.target == common.GetAddonName() then
		userMods.SendEvent( "SCRIPT_ADDON_MEM_RESPONSE", { sender = params.target, memUsage = gcinfo() } )
	end
end

-- Clear all variables
function CleanVars ()
	MailList = {}
end

-- Set button to active mode ("collect")
function SetCollectButtonCollect()
	CollectButton:Enable( true )
	CollectButton:SetVal( "button_label", GetLocalizedText( "CollectButton" ) )
end

-- Set button to passive mode ("wait...")
function SetCollectButtonWait()
	CollectButton:Enable( false )
	CollectButton:SetVal( "button_label", GetLocalizedText( "WaitButton" ) )
end

-- Extracts all items
function CollectItems ( mailID )
	mailBox.ExtractMailItems( mailID, nil )
end

-- Extracts money
function CollectMoney ( mailID )
	mailBox.ExtractMailMoney( mailID )
end

-- EVENT_MAIL_EXTRACT_ITEMS_RESULT
function OnMailExctractItemsResult( result )
	local mailId = result["mailId"]
	local sysResult = result["sysResult"]
	
	if sysResult == "ENUM_MailServiceReply_Succeeded" then
		local mailInfo = mailBox.RequestMailInfo( mailId ) 
		if mailInfo then
			if mailInfo.header then
				if mailInfo.header.hasMoney == false then
					mailBox.DeleteMail( mailId )
				end
			end
		end
	else
		DelIndex = DelIndex - 1
	end	
end

-- EVENT_MAIL_EXTRACT_MONEY_RESULT
function OnMailExctractMoneyResult( result )
	local mailId = result["mailId"]
	local sysResult = result["sysResult"]
	
	if sysResult == "ENUM_MailServiceReply_Succeeded" then
		local mailInfo = mailBox.RequestMailInfo( mailId ) 
		if mailInfo then
			if mailInfo.header then
				if mailInfo.header.hasItems == false then
					mailBox.DeleteMail( mailId )
				end
			end
		end
	else
		DelIndex = DelIndex - 1
	end
end

-- EVENT_MAIL_DELETE_RESULT
function OnMailDeleteResult( result )
	local mailId = result["mailId"]
	local sysResult = result["sysResult"]
	
	--if sysResult == "ENUM_MailServiceReply_Succeeded" then
	--	LogInfo( "delted" )
	--end
	
	DelIndex = DelIndex - 1
	
	if DelIndex <= 0 then
		DeletingFinished ()
	end
end

-- Enumerate all letter in @MailList table and go to OnMailsChanged handler to
-- collect items and money
function EnumLetters ()
	common.RegisterEventHandler(OnMailsChanged, "EVENT_MAILS_CHANGED")
	common.RegisterEventHandler(OnMailExctractItemsResult, "EVENT_MAIL_EXTRACT_ITEMS_RESULT")
	common.RegisterEventHandler(OnMailExctractMoneyResult, "EVENT_MAIL_EXTRACT_MONEY_RESULT")
	common.RegisterEventHandler(OnMailDeleteResult, "EVENT_MAIL_DELETE_RESULT")
	
	common.UnRegisterEventHandler(OnMailExctractResultEx, "EVENT_MAIL_EXTRACT_ITEMS_RESULT")
	common.UnRegisterEventHandler(OnMailExctractResultEx, "EVENT_MAIL_EXTRACT_MONEY_RESULT")
	
	DelIndex = GetTableSize( MailList )
	
	for i = 0, GetTableSize( MailList ) - 1 do
		local mailInfo = mailBox.RequestMailInfo( MailList[i] )
		
		if mailInfo then
			if mailInfo.header then
				OnMailsChanged({ [0] = MailList[i] })
			end
		end
	end
end

-- Called when all letters is deleted (process ended)
function DeletingFinished ()
	common.UnRegisterEventHandler(OnMailsChanged, "EVENT_MAILS_CHANGED")
	common.UnRegisterEventHandler(OnMailExctractItemsResult, "EVENT_MAIL_EXTRACT_ITEMS_RESULT")
	common.UnRegisterEventHandler(OnMailExctractMoneyResult, "EVENT_MAIL_EXTRACT_MONEY_RESULT")
	common.UnRegisterEventHandler(OnMailDeleteResult, "EVENT_MAIL_DELETE_RESULT")
	
	common.RegisterEventHandler(OnMailExctractResultEx, "EVENT_MAIL_EXTRACT_ITEMS_RESULT")
	common.RegisterEventHandler(OnMailExctractResultEx, "EVENT_MAIL_EXTRACT_MONEY_RESULT")
	
	StopProcess()	
end

-- EVENT_MAILBOX_ACTIVATED
function OnMailBoxActivated ()
	StopProcess()
	CollectButton:Show( true )
end

-- EVENT_MAILBOX_CLOSED
function OnMailBoxClosed ()
	CollectButton:Show( false )
	StopProcess()
end

-- EVENT_MAIL_EXTRACT_ITEMS_RESULT (EXTENDED)
-- EVENT_MAIL_EXTRACT_MONEY_RESULT (EXTENDED)
function OnMailExctractResultEx( result )
	local mailId = result["mailId"]
	local sysResult = result["sysResult"]
	
	if sysResult == "ENUM_MailServiceReply_Succeeded" then
		local mailInfo = mailBox.RequestMailInfo( mailId ) 
		if mailInfo then
			if mailInfo.header then
				if mailInfo.header.hasMoney == false and mailInfo.header.hasItems == false then
					mailBox.DeleteMail( mailId )
				end
			end
		end
	end
end

--EVENT_MAILS_CHANGED
function OnMailsChanged ( mailIds )
	for index, mailId in mailIds do
		local mailInfo = mailBox.RequestMailInfo( mailId )
		if mailInfo then
			if mailInfo.header then
				if mailInfo.body then
					local flgFull = true
					if mailBox.IsReady() then
						if mailInfo.header.hasMoney then
							CollectMoney( mailId )
							--MODIF
							if mailInfo.body.money and mailInfo.header.participantName then
								local valuemoney = mailInfo.body.money
								valuemoney = valuemoney/10000
								if valuemoney ~= 0 then
									local valuename = userMods.FromWString(mailInfo.header.participantName)
									local valuetax = userMods.FromWString(common.FormatInt(valuemoney, "%d"))
									local strout = "TaxRecordAddon: NOM " .. valuename .. " VAL " .. valuetax
									common.LogInfo(" ", strout)
								end
							end
							--ENDMODIF
							flgFull = false
						end
						
						if mailInfo.header.hasItems then
							CollectItems( mailId )
							flgFull = false
						end
						
						if flgFull then
							-- Deleting void letter
							mailBox.DeleteMail( mailId )				
						end
					end
				else
					-- Delay extraction
					mailBox.ReadMail( mailId )
				end
			end
		end
	end
end

function StopProcess()
	IsRunned = false
	common.UnRegisterEventHandler(OnMailBoxChanged, "EVENT_MAILBOX_CHANGED")
	SetCollectButtonCollect()
end

-- EVENT_MAILBOX_CHANGED
function OnMailBoxChanged ()
	if IsRunned == false then
		return
	end
	
	
	local info = mailBox.GetInfo()
	if info == nil then
		StopProcess()
		return
	end
	
	local mailIds = mailBox.RequestMailIds()
	if GetTableSize( mailIds ) == 0 then
		StopProcess()
		return
	end	
	
	for j = 0, GetTableSize( mailIds ) - 1 do
		MailList[info.currentPage*7 + j] = mailIds[j]
	end
	
	if info.currentPage == info.pageCount - 1 then	
		IsRunned = false
		common.UnRegisterEventHandler(OnMailBoxChanged, "EVENT_MAILBOX_CHANGED")
		
		EnumLetters()
	else
		mailBox.NextPage()
	end
end

-- OnCollectButtonReaction
function OnCollectButtonReaction ()
	common.RegisterEventHandler(OnMailBoxChanged, "EVENT_MAILBOX_CHANGED")
	
	if mailBox.IsActive() then
		local info = mailBox.GetInfo()
		if info then 
			SetCollectButtonWait()
			IsRunned = true
			MailList = {}
			
			if info.currentPage > 0 then
				mailBox.FirstPage()
			else
				userMods.SendEvent( "EVENT_MAILBOX_CHANGED", {} )
			end
		end
	end
end


--------------------------------------------------------------------------------
-- INITIALIZATION
--------------------------------------------------------------------------------

function Init()

	-- MODIF
	common.RegisterEventHandler( UnknowSlashCommand, "EVENT_UNKNOWN_SLASH_COMMAND" )
	common.RegisterEventHandler( myAvatarCreated, "EVENT_AVATAR_CREATED" )
end
function myAvatarCreated( params )
	local avatarName = object.GetName( avatar.GetId () ) 
	if not (( common.CompareWString ( avatarName, userMods.ToWString("Flibelle")) == 0 ) or 
			( common.CompareWString ( avatarName, userMods.ToWString ("Picsouu")) == 0 )) then
		return
	end
	-- ENDMODIF
	
	-- BUTTONSb
	CollectButton = mainForm:GetChildChecked("CollectButton", false)
	
	-- ADDON MANAGER HANDLERS
	common.RegisterEventHandler( OnAMAddonInfoRequest, "SCRIPT_ADDON_INFO_REQUEST" )
	common.RegisterEventHandler( OnAMAddonMemoryRequest, "SCRIPT_ADDON_MEM_REQUEST" )
	
	-- EVENT HANDLERS
	common.RegisterEventHandler( PostInit, "EVENT_AVATAR_CREATED" ) -- Second part of initialization.
	
	common.RegisterEventHandler(OnMailBoxActivated, "EVENT_MAILBOX_ACTIVATED")
	common.RegisterEventHandler(OnMailBoxClosed, "EVENT_MAILBOX_CLOSED")
	
	common.RegisterEventHandler(OnMailExctractResultEx, "EVENT_MAIL_EXTRACT_ITEMS_RESULT")
	common.RegisterEventHandler(OnMailExctractResultEx, "EVENT_MAIL_EXTRACT_MONEY_RESULT")
	
	-- REACTION HANDLERS
	common.RegisterReactionHandler(OnCollectButtonReaction, "CollectButtonReaction")
	
	-- Backward compatibility with pre-1.1.04 versions:
	if not social.GetFriendInfo then
		mainForm:SetPriority( 2000 )
	end
	-- P.S. In AO 2.0.03, priority changed from 4501 to 4701.
	
	mainForm:SetPriority( 5750 )
	
	-- Continue now (or later)?
	if avatar.IsExist() then
		PostInit()
	end
	
end

function PostInit()
	-- LOCALIZATION
	localization = GetGameLocalization()
	if not common.GetAddonRelatedTextGroup( localization ) then
		localization = "eng"
	end
	
	--COMMON INIT
	mainForm:Show( true )
	OnAMAddonInfoRequest( { target = common.GetAddonName() } )
	
	--ADDITIONAL INIT
	CleanVars()
	if mailBox.IsActive() then
		OnMailBoxActivated ()
	end
end

--------------------------------------------------------------------------------
Init()
--------------------------------------------------------------------------------